﻿using System;
using System.Collections.Generic;
using System.Text;

namespace RuoTeng.Util.Auth
{  
    /// <summary>
    /// 软件授权信息获取以及软件版本更新检测信息
    /// </summary>
    public class Authorization
    {  
        public  static string  UpdateError       = "运行更新更新程序出错";
        public  static string  NotFoundServer    = "程序无法连接服务器获取信息";
        public  static string  NotFoundAuth      = "无法连接到服务器获取授权信息。请尝试重新获取。";
        public  static string  NotExpire         = "软件已过期无法正常使用,请购买。";
        public  static string  FirstGetServer    = "系统正在请求获取服务器,获取授权信息。";


        /// <summary>
        /// 获取授权验证返回的消息
        /// </summary>
        public static string AuthMessage
        {
            get {
                if (SoftWareInfo.FisrtGetServer)
                {
                    return FirstGetServer;
                }
                else if ((SoftWareInfo.endtime == null || SoftWareInfo.endtime == "") || (SoftWareInfo.isend == null || SoftWareInfo.isend == ""))               
                {
                    return NotFoundAuth;
                }
                else
                {
                    return NotExpire;
                }
            }
        }
       
        /// <summary>
        /// 服务器授权验证
        /// </summary>
        /// <param name="sorted">参数(key-value)</param>
        /// <returns></returns>
        public bool DoAuthorization(out SortedList<string, object> sorted)
        {
            sorted = new SortedList<string, object>();
            try
            {
                //旧机器码算法
                string oldmcode     =  MachineCode.GetMachinecode();
                //新机器码算法
                SoftWareInfo.mc     =  MachineCode.GetNewMachinecode();
                //更新机器码
                string addurl       =  SoftWareInfo.web_addmc + oldmcode + "&newcode=" + SoftWareInfo.mc;
                SoftWareInfo.GetData(addurl);
                //------------------------------------------------------------------------------------------------------------------
                //检测该机器码是否有效
                SoftWareInfo.isend   =  DES.DESDeCode(SoftWareInfo.GetData(SoftWareInfo.web_isend + SoftWareInfo.mc), SoftWareInfo.skey);
                //检测该机器码是是否过期 
                SoftWareInfo.endtime =  SoftWareInfo.GetData(SoftWareInfo.web_getendtime + SoftWareInfo.mc);
                //检测该软件是否试用版
                SoftWareInfo.isdemo  =  SoftWareInfo.GetData(SoftWareInfo.web_isdemo + SoftWareInfo.mc);
                //------------------------------------------------------------------------------------------------------------------
                if (SoftWareInfo.isdemo == "")
                {
                    SoftWareInfo.isdemo = SoftWareInfo.GetData(SoftWareInfo.web_isdemo + SoftWareInfo.mc);
                }

                if (SoftWareInfo.isend == SoftWareInfo.mc + "can use")
                {
                    sorted.Add("isend",   SoftWareInfo.isend);
                    sorted.Add("demo",   (SoftWareInfo.isdemo == "0" ? "正式版" : "试用版"));
                    sorted.Add("isdemo", (SoftWareInfo.isdemo == "0" ? false : true));
                    sorted.Add("vip",     true);                    
                }
                else
                {
                    //添加机器码
                    SoftWareInfo.GetData(addurl);
                    sorted.Add("isend",   SoftWareInfo.isend);
                    sorted.Add("demo",   (SoftWareInfo.isdemo == "0" ? "正式版" : "试用版"));
                    sorted.Add("isdemo", (SoftWareInfo.isdemo == "0" ? false : true));
                    sorted.Add("vip",     false);
                }
                string cVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                sorted.Add("notes",      SoftWareInfo.GetData(SoftWareInfo.web_updatelog));
                sorted.Add("endtime",    SoftWareInfo.endtime);
                SoftWareInfo.FisrtGetServer = false;
            }
            catch
            {
                SoftWareInfo.FisrtGetServer = false;
                return false;
            }
            return true;
        }

        /// <summary>
        /// 检测是否存在升级版本
        /// </summary>
        /// <returns></returns>
        public bool CheckUpdate()
        {
            try
            {
                //获取程序的版本号
                //Exe程序中的版本号
                string exeVersion    = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                // 服务器的版本号
                string serverVersion = RuoTeng.Util.Update.UpdateVersion.GetLatestVersion();

                if (serverVersion == "")
                {
                    return true;
                }
                bool boolVersion = RuoTeng.Util.Version.Compare(exeVersion,serverVersion, RuoTeng.Util.VersionCompare.Lt);
                //已经更新过了 将最新的版本写入配置文件中
                if (boolVersion)
                {
                    if (System.IO.File.Exists("Update.exe"))
                    {
                        try
                        {
                            System.Diagnostics.Process.Start("Update.exe");
                        }
                        catch (Exception)
                        {                          
                            return false;
                        }
                    }
                }
                else
                { //检测Exe程序中的版本号,是否大于版本控制文件中的版本号,如果大于则更像配置文件中的版本号
                    string configVersion = RuoTeng.Util.Update.UpdateConfig.GetValue("Version");
                    if (RuoTeng.Util.Version.Compare(exeVersion, configVersion, RuoTeng.Util.VersionCompare.Gt))
                    {
                        RuoTeng.Util.Update.UpdateConfig.SetValue("Version", exeVersion);
                    }
                }
            }
            catch { }
            return true;
        }

        /// <summary>
        /// 检测软件是否已经过期
        /// </summary>
        /// <returns>返回值,没有过期返回False,过期返回True</returns>
        public bool Expire()
        {
            DateTime datetime = Convert.ToDateTime(RuoTeng.Util.Auth.SoftWareInfo.endtime);
            TimeSpan left     = new TimeSpan(datetime.Ticks);
            TimeSpan now      = new TimeSpan(System.DateTime.Now.Ticks);
            int days = left.Days - now.Days;

            if (RuoTeng.Util.Auth.SoftWareInfo.isend != RuoTeng.Util.Auth.SoftWareInfo.mc + "can use" || !(days > 0))
            {
                return false;
            }
            else
            {
                return true;
            }
        }        
    }
}
